package kamikaze.service.product;

import java.io.IOException;
import java.util.Arrays;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kamikaze.bean.Product;
import kamikaze.service.ErrorHandler;
import kamikaze.utils.Database;
import kamikaze.utils.Database.Template;

public class ViewProductServlet extends HttpServlet {

	private static final long serialVersionUID = 8893073591949971239L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		new ErrorHandler(Arrays.asList("Method is not supported")).handle(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		
		final String id = req.getParameter("id");
		if (id != null && !id.isEmpty()) {
			
			try {

				Product product = (Product) Database.get().execute(
						new Template<Object>() {

							@Override
							public Object query(EntityManager em) {

								Query q = em
										.createQuery("Select p from Product p where p.productId= :productId");
								q.setParameter("productId", Long.valueOf(id));
								Product product = (Product) q.getSingleResult();

								return product;
							}
						});

				
				req.setAttribute("product", product);
				req.getRequestDispatcher("/productdetail.jsp").forward(req, resp);
				
			} catch (Exception ex) {
				new ErrorHandler(Arrays.asList(ex.getMessage())).handle(req,
						resp);
				return;
			}

		} else {
			ErrorHandler errorHandler = new ErrorHandler();
			errorHandler.addErrorMessageIfNotNull("Product ID is unknown");
			errorHandler.handle(req, resp);
			return;
		}

	}

}
